const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const cellSize = 20;
const rows = canvas.height / cellSize;
const cols = canvas.width / cellSize;

// 连接WebSocket
const socket = io();
let gameRoom = null;
let players = {};
let currentPlayerId = null;
let coins = 0;

// 获取金币数量
fetch('/api/game/coins')
  .then(res => res.json())
  .then(data => {
    coins = data.coins;
    updateCoinDisplay();
  });

// 更新金币显示
function updateCoinDisplay() {
  document.getElementById('coin-display').textContent = `金币: ${coins}`;
}

// 兑换金币
document.getElementById('convert-coins').addEventListener('click', () => {
  const amount = parseInt(document.getElementById('convert-amount').value);
  if (isNaN(amount) || amount <= 0) {
    alert('请输入有效的金币数量');
    return;
  }

  fetch('/api/game/convert', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ coins: amount })
  })
  .then(res => res.json())
  .then(data => {
    if (data.error) {
      alert(data.error);
    } else {
      coins = data.remaining;
      updateCoinDisplay();
      alert(`成功兑换 ${data.converted} 个投币!`);
    }
  });
});

// 初始化游戏
function initGame() {
  // 加入游戏房间
  socket.emit('join_game');
  
  // 监听游戏状态更新
  socket.on('game_state', (state) => {
    players = state.players;
    food = state.food;
    draw();
  });

  // 监听游戏结束
  socket.on('game_over', (result) => {
    gameRunning = false;
    coins += result.coins;
    updateCoinDisplay();
    alert(`游戏结束! 获得 ${result.coins} 金币!`);
  });

  // 监听玩家加入
  socket.on('player_joined', (playerId) => {
    currentPlayerId = playerId;
  });
}

// 绘制游戏
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制所有玩家
  Object.entries(players).forEach(([id, player]) => {
    ctx.fillStyle = id === currentPlayerId ? 'green' : 'blue';
    player.snake.forEach(segment => {
      ctx.fillRect(segment.x * cellSize, segment.y * cellSize, cellSize, cellSize);
    });
  });

  // 绘制食物
  ctx.fillStyle = 'red';
  ctx.fillRect(food.x * cellSize, food.y * cellSize, cellSize, cellSize);
}

// 键盘控制
document.addEventListener('keydown', (e) => {
  if (!currentPlayerId) return;
  
  let newDirection = null;
  switch (e.key) {
    case 'ArrowUp':
      newDirection = { x: 0, y: -1 };
      break;
    case 'ArrowDown':
      newDirection = { x: 0, y: 1 };
      break;
    case 'ArrowLeft':
      newDirection = { x: -1, y: 0 };
      break;
    case 'ArrowRight':
      newDirection = { x: 1, y: 0 };
      break;
  }
  
  if (newDirection) {
    socket.emit('player_move', { direction: newDirection });
  }
});

// 开始游戏
initGame();